//
//  EGORefreshTableHeaderView.m
//  eNew
//
//  Created by 李佳骏 on 15-4-30.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "EGORefreshTableHeaderView.h"

#define TEXT_COLOR	 [UIColor colorWithRed:87.0/255.0 green:108.0/255.0 blue:137.0/255.0 alpha:1.0]

#define FLIP_ANIMATION_DURATION 0.18f


//设置私有接口。只能本类来使用
@interface EGORefreshTableHeaderView (Private)

- (void)setState:(EGOPullRefreshState)aState;

@end

@implementation EGORefreshTableHeaderView

@synthesize delegate = _delegate;


#pragma mark 初始化initWithFrame
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        // self.view 自使用bounds的宽度
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        
        // 背景色
        self.backgroundColor = [UIColor colorWithRed:226. / 255. green:231. / 255. blue:237. / 255. alpha:1.];
        
#warning 就是泻药
        
        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 10.f, self.frame.size.width, 10.f)] autorelease];
        
        // self.view 自使用bounds的宽度
        label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        
        // 字体
        label.font = [UIFont systemFontOfSize:12.f];
        
        label.textColor = TEXT_COLOR;
        
        // label 文本阴影颜色
        label.shadowColor = [UIColor colorWithWhite:.9f alpha:1.f];
        
        // label 阴影偏移量
        label.shadowOffset = CGSizeMake(0.f, 1.f);
        
        label.backgroundColor = [UIColor clearColor];
        
        // 对齐方法
        label.textAlignment = UITextAlignmentCenter;
        
        [self addSubview:label];
        
        _lastUpdatedLabel = label;
        
        // [label release];
        
        
        label = [[[UILabel alloc] initWithFrame:CGRectMake(0.f, 28.f, self.frame.size.width, 20.f)] autorelease];
        
        // self.view 自使用bounds的宽度
        label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        
        label.textColor = TEXT_COLOR;
        
        // label 文本阴影颜色
        label.shadowColor = [UIColor colorWithWhite:.9f alpha:1.f];
        
        // 阴影偏移量
        label.shadowOffset = CGSizeMake(0.0f, 1.f);
        
        label.backgroundColor = [UIColor clearColor];
        
        // 对齐方式：中心对齐
        label.textAlignment = UITextAlignmentCenter;
        
        _statusLabel = label;
        
        //  [label release];
        
#warning 没准改+
        //初始化图片大小
        CircleView *circleView = [[[CircleView alloc] initWithFrame:CGRectMake(10, 5, 20, 20)] autorelease];
        
        _circleView = circleView;
        
        [self addSubview:circleView];
        
        //  [_circleView release];
        
        
        UIActivityIndicatorView *view = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
#warning 这也是
        // 视图大小
        view.frame = CGRectMake(25.f, frame.size.height - 38.f, 20.f, 20.f);
        
        [self addSubview:view];
        
        _activityView = view;
        
        //  [view release];
        
        [self setState:EGOOPullRefreshNormal];
        
        
    }
    return self;
}


#pragma mark setter

// 获取最后一次更新时间
- (void)refreshLastUpdatedDate
{
    if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDataSourceLastUpdated:)]) {
        
        NSDate *date = [_delegate egoRefreshTableHeaderDataSourceLastUpdated:self];
        
        // NSDateFormatter实例创建字符串。 来表示NSDate 和 NSCalendarDate脆响，已预订格式化字符串输出
        NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
        
        // 设置上午符号
        [formatter setAMSymbol:@"AM"];
        
        // 设置下午符号
        [formatter setPMSymbol:@"PM"];
        
        // 设置时间格式
        [formatter setDateFormat:@"MM/dd/yyyy hh:mm:ss"];
        
        _lastUpdatedLabel.text = [NSString stringWithFormat:@"Last Updated: %@", [formatter stringFromDate:date]];
        
        // 存储_lastUpdatedLabel.text内容，放到字典中
        [[NSUserDefaults standardUserDefaults] setObject:_lastUpdatedLabel.text forKey:@"EGORefreshTableView_LastRefresh"];
        
        // 将NSUserDefaults存储数据放到磁盘        // 同步到
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    } else {
        
        _lastUpdatedLabel.text = nil;
        
    }
}


- (void)setState:(EGOPullRefreshState)aState
{
    switch (aState) {
            
            // 触摸屏幕下拉状态
        case EGOOPullRefreshPulling:
            
            // 松开即刷新
            _statusLabel.text = NSLocalizedString(@"Release to refresh", @"Release to refresh status");
            
            //设置下拉刷新过程，箭头的图片的一个动画过程
            [CATransaction begin];
            
            // 动画时间
            [CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
            
            // 下拉刷新箭头的一个翻转过程                         // 角度幻化为弧度
            _arrowImage.transform = CATransform3DMakeRotation((M_PI / 180.) * 180.f, 0.f, 0.f, 1.f);
            
            // 动画结束
            [CATransaction commit];
            
            break;
            
            // 刚开始接触屏幕准备下拉时候的状态
        case EGOOPullRefreshNormal:
            
            if (_state == EGOOPullRefreshPulling) {
                
                //设置下拉刷新过程
                [CATransaction begin];
                
                // 动画时间
                [CATransaction setAnimationDuration:FLIP_ANIMATION_DURATION];
                
                // 图片转化动画
                _arrowImage.transform = CATransform3DIdentity;
                
                // 动画结束
                [CATransaction commit];
                
            } else {
            
                _circleView.progress = 0;
                
                [_circleView setNeedsDisplay];
            }
            
            // 下拉可以刷新
            _statusLabel.text = NSLocalizedString(@"Pull down to refresh...", @"Pull down to refresh status");
            
            // 停止动画
            [_activityView stopAnimating];
            
            //设置下拉刷新过程
            [CATransaction begin];
            
            // 下拉刷新完成好就不需要下拉动画，此时_activityView动画显示
            
            // 显示关闭动画效果 kCFBooleanTrue关闭 kCFBooleanFalse 开启
            [CATransaction setValue:(id)kCFBooleanTrue forKey:
             kCATransactionDisableActions];
            
            // 设置是否隐藏
            _arrowImage.hidden = NO;
            
            // 设置动画
            _arrowImage.transform = CATransform3DIdentity;
            
            // 动画结束
            [CATransaction commit];
            
            [self refreshLastUpdatedDate];
            
            break;
            
            // 触摸手指松开。完成下拉操作的状态
        case EGOOPullRefreshLoading:
            
            // 加载
            _statusLabel.text = NSLocalizedString(@"Loading", @"Loading Status");
            
            [_activityView startAnimating];
            
            [CATransaction begin];
            
            
            [CATransaction setValue:(id)kCFBooleanTrue forKey:
             kCATransactionDisableActions];
            
            _arrowImage.hidden = YES;
            
            [CATransaction commit];
            
            CABasicAnimation* rotate =  [CABasicAnimation animationWithKeyPath: @"transform.rotation.z"];
            
            rotate.removedOnCompletion = FALSE;
            
            rotate.fillMode = kCAFillModeForwards;
            
            [rotate setToValue: [NSNumber numberWithFloat: M_PI / 2]];
            
            // 重复次数
            rotate.repeatCount = 11;
            
            // 持续
            rotate.duration = 0.25;
            // 累加的
            rotate.cumulative = TRUE;
            
            // 时间设置函数
            rotate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
            
            // 旋转动画
            [_circleView.layer addAnimation:rotate forKey:@"rotateAnimation"];
            
            break;
            
        default:
            
            break;
    }
    _state = aState;
}

#pragma mark ScrollView Methods

#pragma begin
- (void)egoRefreshScrollViewWillBeginScroll:(UIScrollView *)scrollView
{
    
    
    BOOL _loading = NO;
    
    if ([_delegate respondsToSelector:@selector
         (egoRefreshTableHeaderDataSourceIsLoading:)]) {
        
        _loading = [_delegate egoRefreshTableHeaderDataSourceIsLoading:self];
        
    } else if (!_loading) {
        
        [self setState:EGOOPullRefreshNormal];
    }
}

#pragma mark did
- (void)egoRefreshScrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (_state == EGOOPullRefreshLoading) {
        
        CGFloat offSet = MAX(scrollView.contentOffset.y * -1, 0);
        
        offSet = MIN(offSet, 60);
        
        scrollView.contentInset = UIEdgeInsetsMake(offSet, 0.f, 0.f, 0.f);
        
        // 拖动
    } else if (scrollView.isDragging) {
        
        BOOL _loading = NO;
        
        if ([_delegate respondsToSelector:@selector
             
             (egoRefreshTableHeaderDataSourceIsLoading:)]) {
            
            _loading = [_delegate egoRefreshTableHeaderDataSourceIsLoading:self];
            
        } else if (_state == EGOOPullRefreshPulling && scrollView.contentOffset.y >
                   
                   -65.f && scrollView.contentOffset.y < 0.f && !_loading) {
            
            [self setState:EGOOPullRefreshNormal];
            
            
        } else if (_state == EGOOPullRefreshNormal && scrollView.contentOffset.y < -15.f &&!_loading) {
            
            float moveY = fabsf(scrollView.contentOffset.y);
            
            if (moveY >65) {
                
                moveY = 65;
                
                _circleView.progress = (moveY - 15) / (65 - 15);
                
                [_circleView setNeedsDisplay];
            }
        }
        
        // 设置下拉属性scrollView框架回复初始位置
        if (scrollView.contentInset.top != 0) {
            
            scrollView.contentInset = UIEdgeInsetsZero;
        }
        
        
    }
    
}

#pragma mark didEnd
- (void)egoRefreshScrollViewDidEndDragging:(UIScrollView *)scrollView
{
    
    BOOL _loading = NO;
    
    if ([_delegate respondsToSelector:@selector
         
         (egoRefreshTableHeaderDataSourceIsLoading:)]) {
        
        _loading = [_delegate egoRefreshTableHeaderDataSourceIsLoading:self];
    }
    
    if (scrollView.contentOffset.y <= - 65.0f && !_loading) {
        
        if ([_delegate respondsToSelector:@selector(egoRefreshTableHeaderDidTriggerRefresh:)]) {
            
            [_delegate egoRefreshTableHeaderDidTriggerRefresh:self];
        }
        
        [self setState:EGOOPullRefreshLoading];
        
        [UIView beginAnimations:nil context:NULL];
        
        [UIView setAnimationDuration:0.2];
        
        scrollView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
        
        [UIView commitAnimations];
        
    }
    
}


#pragma mark 数据加载完成后调用的方法
- (void)egoRefreshScrollViewDataSourceDidFinishedLoading:(UIScrollView *)scrollView
{
    [UIView beginAnimations:nil context:NULL];
    
    [UIView setAnimationDuration:.3];
    
    // 加载数据完成后，scrollView恢复位置大小
    [scrollView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
    
    [UIView commitAnimations];
    
    double delayInSeconds = 0.2;
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        
        [_circleView.layer removeAllAnimations];
        
    });
    
    // 数据加载完成
    [self setState:EGOOPullRefreshNormal];
    
}

#pragma mark dealloc

- (void)dealloc
{
    [_delegate release];
    
    [_activityView release];
    
    [_arrowImage release];
    
    [_lastUpdatedLabel release];
    
    [super dealloc];
    
}



@end
